package com.wmh.baseservice.admin.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdRolePermissions;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.UsJoinApply;
import com.wmh.baseservice.user.pojo.UsRolePermissions;
import com.wmh.baseservice.user.service.UsInfoService;
import com.wmh.baseservice.user.service.UsJoinApplyService;
import com.wmh.baseservice.user.service.UsRolePermissionsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "管理员-用户管理相关")
@RestController
@RequestMapping("admin/adUsInfo")
@RequiresRoles("admin")
public class AdUsInfoController {

    @Resource
    private UsInfoService usInfoService;
    @Resource
    private UsRolePermissionsService usRolePermissionsService;
    @Resource
    private UsJoinApplyService usJoinApplyService;
    @Resource
    private HttpServletRequest request;

    @ApiOperation("列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list(PageInfo pageInfo, String usId, String nick, Long inviteId) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort(UsInfo.CREATE_TIME, SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsInfo> pageResult = new PageUtil<UsInfo>(pageInfo).startPage((page, queryWrapper) -> {
            if (CommUtil.checkNull(usId)) {
                queryWrapper.eq(UsInfo.ID, usId);
            }
            if (CommUtil.checkNull(nick)) {
                queryWrapper.like(UsInfo.NICK, nick);
            }
            if(CommUtil.checkNull(inviteId)){
                queryWrapper.eq(UsInfo.INVITE_ID, inviteId);
            }
            queryWrapper.select(UsInfo.getFields(UsInfo.PASSWORD));
            usInfoService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("修改状态")
    @PostMapping("updateStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updateStatus(Long usId) {
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (!CommUtil.checkNull(usInfo)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        usInfo.setStatus(usInfo.getStatus() == 0 ? 1 : 0);
        if (!usInfoService.updateById(usInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("updateInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String updateInfo(Long time, UsInfo usInfo) {
        if (!usInfoService.updateById(usInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION, true);
        }
        return ReturnBody.success();
    }

    @ApiOperation("权限列表(无分页)")
    @PostMapping("listNoPage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String listNoPage(Long id) {
        JSONObject jsonObject = new JSONObject(true);
        List<UsRolePermissions> list = usRolePermissionsService.list(new QueryWrapper<UsRolePermissions>().eq(UsRolePermissions.TYPE, 2).isNull(UsRolePermissions.US_ID));
        List<String> listCheck = usRolePermissionsService.list(new QueryWrapper<UsRolePermissions>().eq(UsRolePermissions.TYPE, 2).eq(UsRolePermissions.US_ID, id)).stream().map(UsRolePermissions::getPermissions).collect(Collectors.toList());
        jsonObject.put("list", list);
        jsonObject.put("listCheck", listCheck);
        return ReturnBody.success(jsonObject);
    }

    @ApiOperation("列表")
    @PostMapping("preList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "type")
    public String list(PageInfo pageInfo, Integer type) {
        pageInfo.setTimeScreen(AdRolePermissions.CREATE_TIME);
        pageInfo.setDefaultSort(AdRolePermissions.CREATE_TIME, SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsRolePermissions> pageResult = new PageUtil<UsRolePermissions>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.isNull(UsRolePermissions.US_ID);
            queryWrapper.eq(UsRolePermissions.TYPE, type);
            usRolePermissionsService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("添加角色/权限")
    @PostMapping("add")
    public String add(String name, String remark, Integer type) {
        UsRolePermissions usRolePermissions = usRolePermissionsService.getOneForUpdate(type == 1 ? new QueryWrapper<UsRolePermissions>().eq(AdRolePermissions.TYPE, type).eq(AdRolePermissions.ROLE, name).isNull(AdRolePermissions.AD_ID)
                : new QueryWrapper<UsRolePermissions>().eq(UsRolePermissions.TYPE, type).eq(UsRolePermissions.ROLE, name).isNull(UsRolePermissions.US_ID));
        if (CommUtil.checkNull(usRolePermissions)) {
            return ReturnBody.error("该角色/权限已存在");
        }
        usRolePermissions = new UsRolePermissions();
        if (type == 1) {
            usRolePermissions.setRole(name);
        } else {
            usRolePermissions.setPermissions(name);
        }
        usRolePermissions.setRemark(remark);
        usRolePermissions.setType(type);
        if (!usRolePermissionsService.save(usRolePermissions)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }

    @ApiOperation("修改角色/权限")
    @PostMapping("update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String update(Long id, String name, String remark, Integer type) {
        UsRolePermissions usRolePermissions;
        usRolePermissions = usRolePermissionsService.getOneForUpdate(type == 1 ? new QueryWrapper<UsRolePermissions>().eq(UsRolePermissions.TYPE, type).eq(UsRolePermissions.ROLE, name).isNull(UsRolePermissions.US_ID)
                : new QueryWrapper<UsRolePermissions>().eq(UsRolePermissions.TYPE, type).eq(UsRolePermissions.ROLE, name).isNull(UsRolePermissions.US_ID));
        if (CommUtil.checkNull(usRolePermissions) && !usRolePermissions.getId().equals(id)) {
            return ReturnBody.error("该角色/权限已存在");
        }
        UsRolePermissions raw = usRolePermissionsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(raw)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        usRolePermissions = new UsRolePermissions();
        usRolePermissions.setId(id);
        if (type == 1) {
            usRolePermissions.setRole(name);
        } else {
            usRolePermissions.setPermissions(name);
        }
        usRolePermissions.setRemark(remark);
        usRolePermissions.setType(type);
        usRolePermissionsService.updateInfo(usRolePermissions, type == 1 ? raw.getRole() : raw.getPermissions());
        return ReturnBody.success();
    }

    @ApiOperation("分配权限")
    @PostMapping("setPer")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String setPer(Long id, String rolePerId) {
        List<UsRolePermissions> usRolePermissionsList = new ArrayList<>();
        List<String> rolePerLongId = JSON.parseArray(rolePerId, String.class);
        rolePerLongId.forEach(item -> {
            UsRolePermissions usRolePermissions = new UsRolePermissions();
            usRolePermissions.setUsId(id).setPermissions(item).setType(2);
            usRolePermissionsList.add(usRolePermissions);
        });
        usRolePermissionsService.setPer(id, usRolePermissionsList);
        return ReturnBody.success();
    }

    @ApiOperation("删除")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String delete(Long id, Integer type) {
        usRolePermissionsService.delete(id, type);
        return ReturnBody.success();
    }

    @ApiOperation("审核列表")
    @PostMapping("auditList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String auditList(PageInfo pageInfo) {
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        PageResult<UsJoinApply> pageResult = new PageUtil<UsJoinApply>(pageInfo).startPage((page, queryWrapper) -> {
            usJoinApplyService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            UsInfo usInfo = usInfoService.getByIdForUpdate(item.getUsId());
            if (!CommUtil.checkNull(usInfo)) {
                throw new ServiceException();
            }
            item.setNick(usInfo.getNick());
            item.setAvatar(usInfo.getAvatar());
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("审核详情")
    @PostMapping("auditDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"id"})
    public String auditDetail(Long id) {
        JSONObject object = new JSONObject();
        //申请人信息
        UsJoinApply usJoinApply = usJoinApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(usJoinApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        object.put("apply",usJoinApply);
        UsInfo usInfo = usInfoService.getByIdForUpdate(usJoinApply.getUsId());
        if (!CommUtil.checkNull(usInfo)){
            throw new ServiceException();
        }
        object.put("nick",usInfo.getNick());
        object.put("avatar",usInfo.getAvatar());
        return ReturnBody.success(object);
    }

    @ApiOperation("审核加盟商")
    @PostMapping("audit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"id", "status"})
    public String audit(Long id, Integer status, String refuseReason) {
        Long adId = (Long) request.getAttribute("id");
        UsJoinApply usJoinApply = usJoinApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(usJoinApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (status == -1) {
            if (!CommUtil.checkNull(refuseReason)) {
                return ReturnBody.error("拒绝原因不能为空");
            }
            usJoinApply.setRefuseReason(refuseReason);
        }
        usJoinApply.setAuditId(adId);
        usJoinApply.setAuditTime(new Date());
        usJoinApply.setStatus(status);
        usJoinApplyService.audit(usJoinApply);
        return ReturnBody.success();
    }
}
